<?php

class Elem_questions_answers_model extends Onecore_Model
{

    public function __construct()
    {
        parent::__construct();
        $this->_name = "elem_answers";
        $this->_id = array("id");
        $this->_fields = array("id","value","description","elem_questions_id","index");
        $this->_fieldsConditions = array("ModuloId"=>"where","name"=>"like","description"=>"like");
        $this->_itemName = "Tipo Pregunta";
        $this->_validations = array(
            array(
                "field"=>"description",
                "label"=>"Respuesta",
                "rules"=>"required"
            )  ,
            array(
                "field"=>"value",
                "label"=>"Valor de la respuesta",
                "rules"=>"required"
            )  ,
            array(
                "field"=>"elem_questions_id",
                "label"=>"Identificador de Pregunta",
                "rules"=>"required"
            )  
        );
    }   
    //permite obtener el formato de respuestas de tipo pareadas
    //question->answer->answer, question->innerAnswers
    public function getInnerAnswersFormat($question, $shuffle=true){
        $aux = $question->answers;
        $aux2 = $question->answers;
        $answers = array();
        $answers2 = array();
        foreach ($aux as $a) {
            if($a->parent == 0){
                foreach ($aux2 as $a2) {
                    if($a2->parent == $a->id){
                        $a->answer = $a2;
                        $answers2[] = $a2;
                    }
                }
                $answers[] = $a;
            }
        }
        if($shuffle)
            shuffle($answers2);
        
        $question->answers = $answers;
        $question->innerAnswers = $answers2;
        return $question;
    }
    public function getRightAnswer($questionId){
        $sql = "select  *
                from    $this->_name 
                where   elem_questions_id = $questionId
                and     value = 1
                limit 1";
        $query = $this->db->query($sql);
        $res = $query->result();       
        if(!empty($res[0])){
            return $res[0];
        }
        return null;
    }
}